package com.ougy.reshop.interceptor;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts2.StrutsStatics;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import com.ougy.reshop.model.Region;
import com.ougy.reshop.service.ISRegion;

public class PlaceInterceptor extends AbstractInterceptor {

        /**
         * 
         */
        private static final long serialVersionUID = 6432307199934079033L;
        private Logger logger = Logger.getLogger(getClass());
        private static final String cookieKey = "reshop_city_id";

        private ISRegion sRegion;

        public ISRegion getSRegion() {
			return sRegion;
		}
        @Resource
		public void setSRegion(ISRegion region) {
			sRegion = region;
		}

		@Override
        public String intercept(ActionInvocation invocation) throws Exception {
                ActionContext actionContext = invocation.getInvocationContext();
                HttpServletRequest request = (HttpServletRequest) actionContext
                                .get(StrutsStatics.HTTP_REQUEST);

                Cookie cookies[] = request.getCookies();
                Cookie sCookie = null;
                String sValue = null;
                String sName = null;
                for (int i = 0; i < cookies.length - 1; i++) {
                        sCookie = cookies[i];
                        sName = sCookie.getName();
                        if (sName.equals(cookieKey)) {
                                sValue = sCookie.getValue();
                                Region city=sRegion.load(Integer.parseInt(sValue));
                                String cityName =city.getName();
                                logger.debug("ȡ�� 取到当前城市id:" + sValue);
                                logger.debug("取得当前城市名:"+cityName);
                                request.setAttribute("city",city);
                                return invocation.invoke();
                        }
                }
                logger.debug("没有取得当前城市");
                addDefaultPlaceCookie(invocation);
                return invocation.invoke();
        }

        private void addDefaultPlaceCookie(ActionInvocation invocation) {
                ActionContext actionContext = invocation.getInvocationContext();
                HttpServletResponse response = (HttpServletResponse) actionContext
                                .get(StrutsStatics.HTTP_RESPONSE);
                Cookie cookie = new Cookie(cookieKey, "197");
                cookie.setMaxAge(60 * 60 * 24 * 30 * 12);
                response.addCookie(cookie);

        }

}